package com.maoning.gulimallssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author : 猫宁
 * @Date: 2021/10/11
 */
@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;


    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token")String token){
        final String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url")String url,
                            Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token,
                            HttpServletResponse response){
        if(!StringUtils.isEmpty(sso_token)){
            return "redirect:" + url + "?token=" + sso_token;
        }

        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String login(String username,
                        String password,
                        String url,
                        HttpServletResponse response){
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(url)){
            //这里简单处理一下,如果用户名和密码都传过来了,整一个uuid存用户名
            //这里的uuid其实就是以后的token令牌
            //然后返回来源处
            //以上三部都是一个服务器过来请求的处理,如果需要多个服务单点登录,则还需要扔一个cookie(token)给来源浏览器
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username);
            final Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            return "redirect:" + url + "?token=" + uuid;
        }
        return "login1";
    }


}
